import {designComponent, onBeforeUnmount, onMounted, reactive} from "@peryl/react-compose";
import {renderReactCase} from "./code-render.utils";
import {createEffects} from "@peryl/utils/createEffects";
import {doNothing} from "@peryl/utils/doNothing";
import {codeGeneratorResourceGetter} from "./code-generator.utils";

export const CodeRender = designComponent({
  name: 'code-render',
  props: {
    code: { type: String }
  },
  setup({ props }) {

    const { effects } = createEffects();

    const state = reactive({
      render: doNothing as (() => any)
    });

    const handler = {
      reload: async () => {
        effects.clear();
        if (!!props.code?.trim().length) {
          const renderResult = await renderReactCase({ code: props.code, getResource: codeGeneratorResourceGetter, });
          state.render = renderResult.render ?? doNothing;
          effects.push(() => {state.render = doNothing;});
        }
      },
    };

    onMounted(() => {handler.reload();});
    onBeforeUnmount(effects.clear);

    return () => state.render();
  },
});
